package com.my.controller;

import com.my.mapper.RoleMapper;
import com.my.pojo.Role;
import com.my.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/role")
public class RoleController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        HttpSession session = req.getSession();
        resp.setContentType("text/html;charset=utf-8");
        String action = req.getParameter("action");
        String result = "";
        SqlSession sqlSession = MyBatisUtil.openSession();
        RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class);
        if(action.equals("show")){
            List<Role> roles = roleMapper.searcherAllRole();
            session.setAttribute("roles",roles);
            result = "role/showAllRole.jsp";
        }
        if(action.equals("preUpdate")){
            String idStr = req.getParameter("id");
            int id = Integer.parseInt(idStr);
            Role role = roleMapper.searcherRoleById(id);
            session.setAttribute("role",role);
            result="role/updateRole.jsp";
        }
        if(action.equals("update")){
            String idStr = req.getParameter("id");
            int id = Integer.parseInt(idStr);
            String roleName = req.getParameter("newRoleName");
            String roleDesc = req.getParameter("newRoleDesc");
            Role role = Role.builder().id(id).roleName(roleName).roleDesc(roleDesc).build();
            roleMapper.updateRole(role);
            sqlSession.commit();
            result="role?action=show";
        }
        resp.sendRedirect(result);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
